<?php

namespace App\Aop;

use Wonfu\Core\Annotations\Valid;
use App\Exception\MethodArgumentNotValidException;
use Doctrine\Common\Annotations\AnnotationReader;
use Ray\Aop\MethodInterceptor;
use Ray\Aop\MethodInvocation;
use Symfony\Component\Validator\Validation;

/**
 * Description of Auth
 *
 * @author vison.cao <visonforcoding@gmail.com>
 */
class RequestValid implements MethodInterceptor
{

    public function invoke(MethodInvocation $invocation)
    {
        $va = Validation::createValidatorBuilder()->enableAnnotationMapping(true)
            ->addDefaultDoctrineAnnotationReader()
            ->getValidator();
        $method = $invocation->getMethod();
        $aReader = new AnnotationReader();
        $mA = $aReader->getMethodAnnotation($method, Valid::class);
        $errors = $va->validate($invocation->getNamedArguments()->offsetGet($mA->paramKey));
        if (count($errors) > 0) {
            $methodArgumentNotValidException = new MethodArgumentNotValidException();
            $methodArgumentNotValidException->setErrors($errors);
            throw $methodArgumentNotValidException;
        }
        return $invocation->proceed();
    }

}
